<template>
  <div v-loading="loading">
    <el-row>
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline">
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model.trim="searchForm.deptName" placeholder="部门名称">
          </el-input>
        </el-form-item>
        <el-form-item label="部门状态" prop="deptStatus">
          <el-select v-model="searchForm.deptStatus" placeholder="部门状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查 询</el-button>
          <el-button @click="resetSearchForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 添加和删除按钮区域 -->
    <el-row class="lz-padding-bottom-15">
      <el-button type="primary" @click="addHandleClick" v-auth="['/dept/saveOrUpdate']">添加</el-button>
    </el-row>


    <el-table
        v-loading="loading"
        border
        :data="deptList"
        row-key="id"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="部门名称"></el-table-column>
      <el-table-column prop="orderNum" label="排序" align="center" width="150"></el-table-column>
      <el-table-column prop="deptStatus" label="状态" :formatter="statusFormat" align="center">
          <template slot-scope="scope">
              <el-tag v-if="scope.row.deptStatus=='0'">{{ statusFormat(scope.row) }}</el-tag>
              <el-tag v-else type="info">{{ statusFormat(scope.row) }}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
              type="text"
              @click="editorHandleClick(scope.row)"
              v-auth="['/dept/saveOrUpdate']"
          >修改
          </el-button>
          <el-button
              type="text"
              @click="addHandleClick(scope.row)"
              v-auth="['/dept/saveOrUpdate']"
          >新增
          </el-button>
          <el-button
              type="text"
              v-if="scope.row.parentId != 0"
              @click="deleteHandleClick(scope.row)"
              v-auth="['/dept/delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑和添加页面定义 -->
    <el-dialog :title="isEditor ? '编辑' : '添加'" width="600px" :visible.sync="dialogAddFormVisible" append-to-body>
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="dialogForm.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="dialogForm.parentId" :options="deptOptions" :normalizer="normalizer"
                          placeholder="选择上级部门"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="dialogForm.deptName" placeholder="请输入部门名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="dialogForm.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="dialogForm.leader" placeholder="请输入负责人" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="dialogForm.phone" placeholder="请输入联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="dialogForm.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态" prop="deptStatus">
              <el-select v-model="dialogForm.deptStatus" placeholder="部门状态">
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>

              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogFormData('dialogForm')" v-if="!isEditor">重 置</el-button>
        <el-button @click="dialogAddFormVisible = false" v-if="isEditor">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: {Treeselect},
  data() {
    return {
      searchDate: "",
      //数据分页
      loading: true,//区域加载
      //数据列表表单
      deptList: [],//数据列表表单的数据域
      deptOptions: [],//部门数组
      tableChecked: [],//批量删除时被选中行
      ids: [],//批量删除的id
      //数据更新
      updateUserId: 0,//编辑时要更新的用户id
      //搜索
      searchForm: {},
      isEditor: false,//标志弹出框是编辑还是添加
      dialogAddFormVisible: false,//编辑表单弹出框是否显示
      dialogForm: { //弹出表单
        deptStatus:"0"
      },
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "上级部门不能为空", trigger: "blur"}
        ],
        deptName: [
          {required: true, message: "部门名称不能为空", trigger: "blur"},
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        orderNum: [
          {required: true, message: "菜单顺序不能为空", trigger: "blur"}
        ],
        deptStatus: [
          {required: true, message: "请选择部门状态", trigger: "blur"}
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      urls: {
        save: "/dept/save",
        update: "/dept/update",
        search: "/dept/list",
        delete: "/dept/delete",
        find: "/dept/findById",
        exclude: "/dept/exclude",
        exportExcel: "/dept/export",
      },
    };
  },
  created: function () {
    this.getList();
  },
  methods: {
    //加载部门列表
    getList() {
      this.$data.loading = true;
      let url =
          this.$data.urls.search;
      this.axios({
        method: "POST",
        url: url,
        data: this.$data.searchForm,
      })
          .then((res) => {
            this.$data.loading = false;
            let code = res.data.code;
            if (code == 200) {
              this.deptList = this.handleTree(res.data.data, "id");
              this.loading = false;
            } else {
              this.$message.error("加载资源失败");
            }
          })
          .catch((error) => {
            // this.$message.error('加载资源失败');
            console.log(error);
          });

    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children
      };
    },
    onSearch: function () {
      this.getList();
    },

    resetSearchForm: function () {
      //重置表单数据
      this.searchForm = this.$options.data().searchForm;
      this.searchDate = this.$options.data().searchDate;
      this.getList();

    },
    //重置编辑弹出框表单的数据
    resetDialogFormData: function (formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
      }
    },
    addHandleClick: function (row) {
      this.dialogForm = this.$options.data().dialogForm;
      this.$data.isEditor = false;
      this.$data.dialogAddFormVisible = true;
      this.resetDialogFormData('dialogForm');
      //添加的父级部门
      if (row != undefined) {
        this.dialogForm.parentId = row.id;
      }
      let url = this.$data.urls.search;
      this.axios({
        method: "POST",
        url: url,
        data: this.$data.searchForm,
      }).then(response => {
        this.deptOptions = this.handleTree(response.data.data, "id");
      });
    },

    saveOrUpdate: function () {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid && this.checkDialogForm()) {
          //修改操作
          if (this.dialogForm.id != undefined) {


            this.axios({
              method: 'POST',
              url: this.$data.urls.update,
              data: this.dialogForm
            }).then(res => {
              let code = res.data.code
              if (code == 200) {
                this.$message.success('修改成功');
                this.getList();
                this.$data.dialogAddFormVisible = false
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(error => {
              console.log(error);
            });


          } else {
            this.axios({
              method: 'POST',
              url: this.$data.urls.save,
              data: this.dialogForm
            }).then(res => {
              let code = res.data.code
              if (code == 200) {
                this.$message.success('添加成功');
                this.getList();
                this.$data.dialogAddFormVisible = false
              } else{
                this.$message.error(res.data.msg);
              }
            }).catch(error => {
              console.log(error);
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }


      });
    },
    editorHandleClick: function (row) {
      this.$data.loading = true;
      this.isEditor = true;
      let url = this.$data.urls.find + "/" + row.id;
      this.axios({
        method: "GET",
        url: url,
        data: {},
      }).then((res) => {
        this.$data.loading = false;
        let code = res.data.code;
        if (code == 200) {
          this.dialogAddFormVisible = true;
          this.resetDialogFormData('dialogForm');
          this.$nextTick(() => {
            this.$data.dialogForm = res.data.data;
          })
        }
      }).catch((error) => {
        console.log(error)
      });

      let excludeUrl = this.$data.urls.exclude + "/" + row.id;
      this.axios({
        method: "GET",
        url: excludeUrl,
        data: {},
      }).then((res) => {

        let code = res.data.code;
        if (code == 200) {
          this.deptOptions = this.handleTree(res.data.data, "id");

        }
      }).catch((error) => {
        console.log(error)
      });
    },

    /** 删除按钮操作 */
    deleteHandleClick(row) {
      this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.delete(row);
      }).catch((error) => {
        // this.$message.error('加载资源失败');
        console.log(error);
      });
    },
    delete: function (row) {
      let id = row.id;

      let url = this.$data.urls.delete + "?deptId=" + id;

      this.axios({
        method: "GET",
        url: url,
        data: {},
      })
          .then((res) => {
            let code = res.data.code;
            if (code == 200) {
              this.$message.success("删除成功");
              this.getList();
            } else {
              this.$message.warning(res.data.msg);
            }
          })
          .catch((error) => {
            // this.$message.error('加载资源失败');
            console.log(error);
          });
    },

    checkDialogForm() {
      return true;
    },

    // 字典状态字典翻译
    statusFormat(row) {
      if (row.deptStatus == 0) {
        return "正常"
      } else if (row.deptStatus == 1) {
        return "停用"
      }
    },
  },
};
</script>

<style>
</style>